package com.apes.fn.server.productRequireManage.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.mdm.supplierConfiguration.SupplierBusinessScopeService;
import com.apes.fn.server.productRequire.*;
import com.apes.fn.server.productRequireManage.model.ReplenishmentBusinessImpAbstract;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.plugin.soe.store.database.repository.SceneRepository;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.account.tax.repository.TaxRepository;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.contract.repository.ContractRepository;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrder;
import com.apes.scm.pur.purchaseOrder.model.PurchaseOrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service("replePurOrderService")
public class ReplePurOrderService extends ReplenishmentBusinessImpAbstract {

    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private ProductUomRepository productUomRepository;
    @Autowired
    private EnumerationRepository enumerationRepository;
    @Autowired
    private ContrastPartyCodeRepository contrastPartyCodeRepository;
    @Autowired
    private OutboxSubscriberService outboxSubscriberService;
    @Autowired
    private ProductRequireItemRepository productRequireItemRepository;
    @Autowired
    private ProductRequireRepository productRequireRepository;
    @Autowired
    private ProductRequireService productRequireService;

    @Override
    public Map sendOrder(JSONObject getJO) {
        JSONArray itemDataArray = getJO.getJSONArray("item") == null?getJO.getJSONArray("purchaseRequireItems"):getJO.getJSONArray("item");
        String personId = getJO.getString("personId");

        AtomicReference dumpIdStr = new AtomicReference(" ");
        AtomicBoolean cheDataPurFlag = new AtomicBoolean(false);
        Map<JSONObject, List> requireItemGroupPur = this.requireItemGroup(itemDataArray);
        requireItemGroupPur.forEach((k, v) -> {
            PurchaseOrder purchaseOrder = this.appendPurchaseOrder(k, personId);
            List<PurchaseOrderItem> orderItems = this.appendPurchaseOrderItem(v, purchaseOrder);

            if (orderItems.isEmpty()) return;
            cheDataPurFlag.set(true);

            purchaseOrder.setPurchaseItems(orderItems);
            if (k.getBooleanValue("oldInquiry")) { // 生成到老系统
                this.sendOldCGDDLogic(purchaseOrder, k.getString("carLicense"), k.getString("platformId"));
            } else { // 生成到新系统
                PurchaseOrder order = invoke("purchase.order.create", MapUtil.mapped(purchaseOrder));
                dumpIdStr.set(dumpIdStr.get() + order.getId() + "\r\n");
            }
        });

        if (!cheDataPurFlag.get()) throw new RuntimeException("未获取到有效数据！请检查是否填写采购数量");
        return MapUtil.mapper("orderId", dumpIdStr.get());
    }


    // 发送 创建老系统采购订单逻辑
    public void sendOldCGDDLogic(PurchaseOrder purchaseOrder, String carLicense, String platformId) {
        // 根据货源状态分组
        Map<String, List<PurchaseOrderItem>> groupPurchaseOrder = purchaseOrder.getPurchaseItems().stream().collect(
                Collectors.groupingBy(item -> {
                    return item.getSourceState().getId();
                })
        );

        JSONObject cgddObj = this.appendCGDD(purchaseOrder);
        cgddObj.put("CPHM", carLicense);
        cgddObj.put("PTID", platformId);

        ProductRequire require = getBean(ProductRequireRepository.class).findOne(purchaseOrder.getProductRequire());
        groupPurchaseOrder.forEach((k1, v1) -> {
            JSONObject cgddObjClone = JSONObject.parseObject(cgddObj.toJSONString());
            JSONArray CGDDMXArray = new JSONArray();
            v1.forEach(purchaseOrderItem -> {
                if (purchaseOrderItem.getSourceState() != null) {
                    // 拼接采购订单明细
                    CGDDMXArray.add(this.appendCGDDMX(purchaseOrderItem));

                    // 变更订货在途
                    require.getProductRequireItems().forEach(requireItem -> {
                        if (requireItem.getId().equals(purchaseOrderItem.getSourceItemId())) {
                            double newQty = purchaseOrderItem.getUom().computeQty(purchaseOrderItem.getProductUomQty(), requireItem.getUom(), false);
                            requireItem.setOrderQty(newQty);
                        }
                    });
                }
            });


            cgddObjClone.put("PUR_CGDDMX", CGDDMXArray);
            outboxSubscriberService.commonSendRequest("local:ReplenishmentManagementService.synCGDD", "synCGDD Error ! " + purchaseOrder.getProductRequire(), cgddObjClone);
        });

        require.setLastUpdatedStamp(new Date());
        productRequireService.save(require);

    }

    // 获取承运方式
    private String obtainCarrireInfo(String requireId, String supplierId) {
        List<ProductRequireItem> inquiryRequiryItems = productRequireItemRepository.findBySupplierIdAndProductRequireId(supplierId, requireId);
        if (inquiryRequiryItems.isEmpty()) return "";
        ProductRequireItem requireItem = inquiryRequiryItems.get(0);
        List<Map> findCarriers = getBean(ServicePlanItemRepository.class)
                .findCarrier(requireItem.getCommodityInquiryOrderId(), requireItem.getProduct().getId(), requireItem.getProductRequire().getSource());
        if (!findCarriers.isEmpty() && !StringUtils.isEmpty(findCarriers.get(0).get("CARRIER_NAME"))) {
            return findCarriers.get(0).get("CARRIER_NAME").toString();
        }
        return "";
    }


    private JSONObject appendCGDD(PurchaseOrder purchaseOrder) {
        JSONObject cgddObj = new JSONObject();
        cgddObj.put("PSFS", this.obtainCarrireInfo(purchaseOrder.getProductRequire(), purchaseOrder.getSupplier().getId()));

        cgddObj.put("CGDDH", "");
        cgddObj.put("CZY", purchaseOrder.getCreator());
        cgddObj.put("DJLXID", "CD0");
        cgddObj.put("DJLXMC", "采购订货单");
        cgddObj.put("BZ", "要货补货管理-采购"); // 固定并使用
        cgddObj.put("LYDJLX", purchaseOrder.getSourceType());
        cgddObj.put("LYDJMC", purchaseOrder.getSourceTypeName());
        cgddObj.put("LYDJHM", purchaseOrder.getProductRequire());
        cgddObj.put("CGHTH", purchaseOrder.getContract().getId());
        cgddObj.put("CGZZID", purchaseOrder.getCompany().getId());
        cgddObj.put("CGZZMC", purchaseOrder.getCompany().getName());

        cgddObj.put("CPHM", purchaseOrder.getCarLicense());
        if (StringUtils.hasText(purchaseOrder.getProductRequire())) {
            ProductRequire productRequire = SpringManager.getBean(ProductRequireRepository.class).findOne(purchaseOrder.getProductRequire());
            if (!Objects.isNull(productRequire.getCustomerExpand())) {
                cgddObj.put("PZCXID", productRequire.getCustomerExpand().getJekunModelCode());
                cgddObj.put("CJHM", productRequire.getCustomerExpand().getVin());
            }
        }

        List<ContrastPartyCode> contrastPartyCode = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("party.id", purchaseOrder.getSupplier().getParty().getId()));
        if (contrastPartyCode.size() == 0) {
            throw new RuntimeException("请配置角色对照表对应的供应商！");
        }
        cgddObj.put("GYSID", contrastPartyCode.get(0).getGysid());
        cgddObj.put("HZFS", "distribution".equals(purchaseOrder.getContract().getCooperation().getId())?0:1);
        String settlementType = purchaseOrder.getContract().getSettlementType().getCode();
        int jszq = "bill".equals(settlementType)?0:"week".equals(settlementType)?1:"halfMonth".equals(settlementType)?2:"month".equals(settlementType)?3:"totalCash".equals(settlementType)?4:"deptCash".equals(settlementType)?5:0;
        cgddObj.put("JSZQ", jszq);
        cgddObj.put("JHFSID", "Contract.carryType.selfMention".equals(purchaseOrder.getContract().getCarryType().getId())?"10":"60");
        cgddObj.put("JHFSMC", "Contract.carryType.selfMention".equals(purchaseOrder.getContract().getCarryType().getId())?"自提":"送货");
        cgddObj.put("DHSX", 0);
        PartyRole ryInfo;
        if (StringUtils.hasText(purchaseOrder.getPurchasingGroup())) {
            List<Map> getPurchaseGroupOperators = invoke("cm.purchasingGroup.getPurchaseGroupOperator", MapUtil.mapper("purchaseingId", purchaseOrder.getPurchasingGroup()));
            if (getPurchaseGroupOperators.isEmpty()) {
                ryInfo = partyRoleRepository.findOne("system");
            } else {
                ryInfo = partyRoleRepository.findOne(getPurchaseGroupOperators.get(0).get("OPERABLE_ID").toString());
            }
        } else {
            ryInfo = partyRoleRepository.findOne("system");
        }

        cgddObj.put("RYID", ryInfo.getId());
        cgddObj.put("RYMC", ryInfo.getName());

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Calendar currentdate = Calendar.getInstance();
        currentdate.add(Calendar.DATE, 30);

        cgddObj.put("YQSHRQ", fmt.format(currentdate.getTime()));

        cgddObj.put("DJZT", 0);
        cgddObj.put("DHZJE", purchaseOrder.getAmtTotal());
        cgddObj.put("RKZJE", 0); // ????
        cgddObj.put("SQYFBJ", 0);

        cgddObj.put("ZDR", partyRoleRepository.findOne(purchaseOrder.getCreator()).getName());
        cgddObj.put("GSID", purchaseOrder.getCompany().getId());
        cgddObj.put("SPSX", 0);
        cgddObj.put("DHZSL", Arith.round(purchaseOrder.getPurchaseItems().stream().mapToDouble(purchaseOrderItem -> purchaseOrderItem.getProductUomQty()).sum(), 2));
        cgddObj.put("ZQTS", 0);
        cgddObj.put("CGZID", purchaseOrder.getPurchasingGroup());

        Map siteInfo = invoke("tms.site.oldPhyDepotAddress", MapUtil.mapper("site_id", purchaseOrder.getSiteId()));
        cgddObj.put("ZDID", purchaseOrder.getSiteId());
        cgddObj.put("ZDMC", siteInfo.get("NAME"));
        cgddObj.put("ZZZSHDZ", siteInfo.get("ADDRESS"));

        return cgddObj;

    }


    private JSONObject appendCGDDMX(PurchaseOrderItem purchaseOrderItem) {
        JSONObject CGDDMXObj = new JSONObject();
        PurchaseOrder purchaseOrder = purchaseOrderItem.getPurchaseOrder();
        CGDDMXObj.put("XH", purchaseOrderItem.getSourceItemId());
        CGDDMXObj.put("CKKQID", purchaseOrder.getLocation().getId());
        CGDDMXObj.put("CKKQMC", purchaseOrder.getLocation().getName());
        CGDDMXObj.put("CKID", purchaseOrder.getLocation().getPhyDepot().getId());
        CGDDMXObj.put("CKMC", purchaseOrder.getLocation().getPhyDepot().getName());
        CGDDMXObj.put("KQID", purchaseOrder.getLocation().getUsage().getId());
        CGDDMXObj.put("KQMC", purchaseOrder.getLocation().getUsage().getName());
        CGDDMXObj.put("CCTJID", 10);
        CGDDMXObj.put("SPID", purchaseOrderItem.getProduct().getId());
        CGDDMXObj.put("SPMC", purchaseOrderItem.getProduct().getName());
        CGDDMXObj.put("PLMC", purchaseOrderItem.getProduct().getClassify().getName());
        CGDDMXObj.put("PPID", purchaseOrderItem.getProduct().getBrand().getId());
        CGDDMXObj.put("PPMC", purchaseOrderItem.getProduct().getBrand().getName());
        CGDDMXObj.put("SPZID", purchaseOrderItem.getProduct().getProductGroup().getId());
        CGDDMXObj.put("SPZMC", purchaseOrderItem.getProduct().getProductGroup().getName());
        CGDDMXObj.put("SPXH", purchaseOrderItem.getProduct().getModel());
        CGDDMXObj.put("GG", purchaseOrderItem.getProduct().getSpecifications());
        CGDDMXObj.put("JLDW", purchaseOrderItem.getUom().getName());
        CGDDMXObj.put("HSBL", purchaseOrderItem.getUom().getFactor());
        CGDDMXObj.put("DHDJ", purchaseOrderItem.getPriceUnit());
        CGDDMXObj.put("DHJS", purchaseOrderItem.getProductUomQty());
        CGDDMXObj.put("DHSL", purchaseOrderItem.getProductUomQty() * purchaseOrderItem.getUom().getFactor());
        CGDDMXObj.put("DHJE", purchaseOrderItem.getPriceTotal());
        CGDDMXObj.put("RKJS", 0);
        CGDDMXObj.put("RKSL", 0);
        CGDDMXObj.put("ZXJS", 0);
        CGDDMXObj.put("ZXSL", 0);
        CGDDMXObj.put("GSID", purchaseOrder.getCompany().getId());
        CGDDMXObj.put("SB", 0);
        CGDDMXObj.put("SSBL", purchaseOrderItem.getTax().getAmt() / 100);
        CGDDMXObj.put("RKZDJS", 0);
        CGDDMXObj.put("RKZDSL", 0);
        CGDDMXObj.put("ZGXJ", purchaseOrderItem.getPriceCeiling());
        CGDDMXObj.put("ZDXJ", 0);
        CGDDMXObj.put("HYZT", purchaseOrderItem.getSourceState().getCode());
        CGDDMXObj.put("KJHJS", 0);
        CGDDMXObj.put("SJDHJS", 0);
        CGDDMXObj.put("YFHJS", 0);
        CGDDMXObj.put("YJDHSC", purchaseOrderItem.getExpectedArrivalTime());
        CGDDMXObj.put("CGDHSC", purchaseOrderItem.getExpectedArrivalTime());
        CGDDMXObj.put("YCKKQID", purchaseOrder.getLocation().getId());
        CGDDMXObj.put("YCKKQMC", purchaseOrder.getLocation().getName());
        CGDDMXObj.put("YGYSID", purchaseOrder.getSupplier().getId());
        CGDDMXObj.put("YGYSMC", purchaseOrder.getSupplier().getName());
        CGDDMXObj.put("YCGZZID", purchaseOrder.getCompany().getId());
        CGDDMXObj.put("YCGZZMC", purchaseOrder.getCompany().getName());
        CGDDMXObj.put("SOLICITATION_QTY", 0);
        return CGDDMXObj;
    }




    // 拼接采购订单
    private PurchaseOrder appendPurchaseOrder(JSONObject expandInfoObj, String personId) {
        PurchaseOrder order = new PurchaseOrder();
        personId = StringUtils.isEmpty(personId)?"system":personId;
        PartyRole createPerple = partyRoleRepository.findOne(personId);
        String sceneId = "004465".equals(expandInfoObj.get("supplierId"))?"PO003":"PO001";
        String purchasingGroupId = expandInfoObj.getString("purchasingGroupId");
        order.setState("sent");
        order.setScene(SpringManager.getBean(SceneRepository.class).findOne(sceneId));
        order.setClerk(createPerple);
        order.setCreator(createPerple.getId());
        order.setCreateUid(createPerple);
        order.setCreateDate(new Date());
        order.setPurchasingGroup(purchasingGroupId);
        order.setCustomerExpandId(expandInfoObj.getJSONObject("customerExpand").getString("id"));

        Contract contract = SpringManager.getBean(ContractRepository.class).findOne(expandInfoObj.getString("contractId"));
        order.setContract(contract);
        order.setCooperation(contract.getCooperation());
        order.setDept(SpringManager.getBean(DeptRepository.class).findOne(expandInfoObj.getString("deptId")));
        order.setSupplier(partyRoleRepository.findOne(expandInfoObj.getString("supplierId")));
        order.setMoveType(contract.getMoveType() == null?enumerationRepository.findOne("direct"):contract.getMoveType());
        order.setLocation(SpringManager.getBean(LocationRepository.class).findOne(expandInfoObj.getString("locationId")));
        order.setCompany(partyRoleRepository.findOne(expandInfoObj.getString("companyId")));
        order.setCarLicense(expandInfoObj.getString("carLicense"));
        order.setProductRequire(expandInfoObj.getString("productRequireId"));
        order.setSource(expandInfoObj.getString("productRequireId"));
        order.setSourceType("ProductRequire");
        order.setSourceTypeName("赋能要货单");
        order.setNote("要货补货管理-采购");
        order.setSiteId(this.obtainSite(expandInfoObj.getString("locationId"), purchasingGroupId, expandInfoObj.getString("siteId")));
        return order;
    }

    // 拼接采购订单明细
    private List<PurchaseOrderItem> appendPurchaseOrderItem(List requireItemArray, PurchaseOrder purOrder) {
        List<PurchaseOrderItem> orderItems = new ArrayList<>();
        requireItemArray.forEach(requireItem -> {
            JSONObject requireItemObj = (JSONObject) requireItem;
            PurchaseOrderItem orderItem = new PurchaseOrderItem();
            double distributionQty = requireItemObj.getDoubleValue("distributionQty");
            double P001 = requireItemObj.getDoubleValue("P001");
            long taxId = requireItemObj.getJSONObject("tax").getLong("id");

            orderItem.setPurchaseOrder(purOrder);
            orderItem.setSourceState(enumerationRepository.findOne(requireItemObj.getString("sourceStateId")));
            orderItem.setProduct(productRepository.findOne(requireItemObj.getJSONObject("product").getString("id")));
            orderItem.setTax(SpringManager.getBean(TaxRepository.class).findOne(taxId));
            orderItem.setUom(productUomRepository.findOne(requireItemObj.getJSONObject("purchaseUom").getLong("id")));
            orderItem.setProductUomQty(distributionQty);
            orderItem.setEffectiveQty(distributionQty);
            orderItem.setDemandQty(distributionQty);
            orderItem.setPriceUnit(P001);

            Map getPriceCondi = new HashMap();
            getPriceCondi.put("companyId", purOrder.getCompany().getId());
            getPriceCondi.put("taxId", taxId);
            getPriceCondi.put("priceUnit", P001);
            getPriceCondi.put("qty", distributionQty);
            Map reponsePrice = invoke("account.tax.computeTaxAmount", getPriceCondi);
            orderItem.setPriceSubtotal(Double.parseDouble(reponsePrice.get("totalExcluded").toString()));
            orderItem.setPriceTax(Double.parseDouble(reponsePrice.get("taxAmt").toString()));
            orderItem.setPriceTotal(Double.parseDouble(reponsePrice.get("totalIncluded").toString()));
            orderItem.setPriceCeiling(requireItemObj.getDoubleValue("priceCeiling"));
            orderItem.setExpectedArrivalTime(requireItemObj.getDoubleValue("expectedArrivalTime"));
            orderItem.setSourceState(enumerationRepository.findOne(requireItemObj.getString("sourceStateId")));
            orderItem.setSourceItemId(requireItemObj.getString("id"));
            orderItems.add(orderItem);
        });
        return orderItems;
    }

    // 获取站点
    private String obtainSite(String locationId, String purchasingGroupId, String siteId) {
        if (StringUtils.hasText(purchasingGroupId) && StringUtils.isEmpty(siteId)) {
            Map purchaseGroupSite = invoke("cm.purchasingGroup.queryPurchaseGroupSite", MapUtil.mapper("id", purchasingGroupId, "locationId", locationId));
            return purchaseGroupSite.get("siteId").toString();
        } else {
            return siteId;
        }
    }

    // 根据 供应商、部门、平台等分组为采购订单拆单做准备
    private Map requireItemGroup(JSONArray itemDataArray) {
        return itemDataArray.stream().collect(Collectors.groupingBy(requireItem -> {
            JSONObject requireItemObj = (JSONObject) requireItem;
            this.requiredParameter(requireItemObj);

            Map key = MapUtil.mapper("companyId", requireItemObj.getJSONObject("company").getString("id"),
                    "supplierId", requireItemObj.getJSONObject("supplier").getString("id"),
                    "deptId", requireItemObj.getJSONObject("dept").getString("id"),
                    "contractId", requireItemObj.getJSONObject("contract").getString("id"),
                    "locationId", requireItemObj.getJSONObject("location").getString("id"),
                    "platformId", requireItemObj.getJSONObject("platform").getString("id"),
                    "productRequireId", requireItemObj.getString("productRequireId"),
                    "customerExpand", requireItemObj.getJSONObject("customerExpand") == null?new JSONObject():requireItemObj.getJSONObject("customerExpand"),
                    "carLicense", requireItemObj.getJSONObject("customerExpand") == null?"":requireItemObj.getJSONObject("customerExpand").getString("carLicense"),
                    "siteId", this.specialColumnObtainValue(requireItemObj.get("site")),
                    "purchasingGroupId", this.specialColumnObtainValue(requireItemObj.get("purchasingGroup")),
                    "oldInquiry", !StringUtils.isEmpty(requireItemObj.get("commodityInquiryOrderId")) && Objects.isNull(requireItemObj.get("channelType")));

            if (StringUtils.isEmpty(key.get("purchasingGroupId"))) throw new RuntimeException("已勾选的数据【采购组】不能为空!!");
            return new JSONObject(key);
        }));
    }

    // 界面选择的是对象，默认传值给界面是 Map
    private String specialColumnObtainValue(Object value) {
        if (value instanceof JSONObject) {
            return ((JSONObject) value).getString("id");
        } else if (value instanceof JSONArray) {
            return ((JSONArray) value).getJSONObject(0).getString("id");
        }
        return "";
    }



    // 必填项提示
    private void requiredParameter(JSONObject requireItemObj) {
        if (requireItemObj.getJSONObject("supplier") == null) throw new RuntimeException("已勾选的数据供应商不能为空!!");
        if (requireItemObj.getJSONObject("company") == null) throw new RuntimeException("已勾选的数据公司不能为空!!");
        if (requireItemObj.getJSONObject("dept") == null) throw new RuntimeException("已勾选的数据部门不能为空!!");
        if (requireItemObj.getJSONObject("contract") == null) throw new RuntimeException("已勾选的数据合同不能为空!!");
    }


    @OutboxSubscriber(id="local:ReplenishmentManagementService.synCGDD", name="要货补货管理-采购同步老框架")
    public void synCGDD(OutboxPayloadWrapper outboxPayloadWrapper) {
        boolean success = false;
        JSONObject result = new JSONObject();
        try {
            result = getBean(PiManager.class).synErp("scmCgddService.insert", outboxPayloadWrapper.getPayload());
            success = result.getBooleanValue("success");
        } catch (Exception e) {
            e.getMessage();
            if (e.getMessage().indexOf("重复生成采购订单！") != -1) {
                e.getMessage();
            } else {
                success = false; // 如果此处有异常，以此异常为准，否则会覆盖
                throw new RuntimeException(e.getMessage());
            }
        } finally {
            if (!success) {
                throw new RuntimeException(result.getString("msg"));
            }
        }
    }

    // 老系统删除 - 修改订货数量
    public void oldCGDDUpdateOrderQty(SimpleRequest request) {
        outboxSubscriberService.commonSendRequest("local:replePurOrderService.updateRequireQty", "oldeCgdd delete ! " + request.getJO().get("id"), request.getJO());
    }

    @OutboxSubscriber(id="local:replePurOrderService.updateRequireQty", name="要货补货管理-老系统删除同步订货数量")
    public void updateRequireQty(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject getJO = JSONObject.parseObject(outboxPayloadWrapper.getPayload());
        ProductRequire require = productRequireRepository.findOne(getJO.getString("id"));

        require.getProductRequireItems().forEach(requireItem -> {
            getJO.getJSONArray("item").forEach(itemObj -> {
                JSONObject itemObjSingle = (JSONObject) itemObj;
                String itemId = itemObjSingle.getString("itemId");

                if (itemId.equals(requireItem.getId())) {
                    double deleteOrderQty = itemObjSingle.getDoubleValue("orderQty");
                    ProductUom purchaseUom = productUomRepository.findBypurchaseUom(requireItem.getProduct().getId());
                    purchaseUom.computeQty(deleteOrderQty, requireItem.getUom(), false);
                    requireItem.setOrderQty(requireItem.getOrderQty() - (requireItem.getOrderQty() > deleteOrderQty?deleteOrderQty:requireItem.getOrderQty()));
                }
            });
        });
        require.setLastUpdatedStamp(new Date());
        productRequireService.save(require);
    }
}
